/*
 * Copyright (C) 2018 justlive1
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package vip.justlive.common.web.util;

import javax.servlet.http.HttpServletRequest;
import vip.justlive.common.base.constant.BaseConstants;

/**
 * web工具类
 * 
 * @author wubo
 *
 */
public class WebUtils {

  private static final String UNKNOWN = "unknown";

  WebUtils() {}

  /**
   * 获取ip
   * 
   * @param request 请求
   * @return ip
   */
  public static String getIpAddr(final HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (checkIp(ip)) {
      return ip;
    }
    ip = request.getHeader("Proxy-Client-IP");
    if (checkIp(ip)) {
      return ip;
    }
    ip = request.getHeader("WL-Proxy-Client-IP");
    if (checkIp(ip)) {
      return ip;
    }
    ip = request.getHeader("X-Real-IP");
    if (checkIp(ip)) {
      return ip;
    }
    ip = request.getRemoteAddr();
    if (checkIp(ip)) {
      return ip;
    }
    // 应对x-forwarded-for 中返回多个服务器ip的情况
    if (ip != null && ip.contains(BaseConstants.COMMA_SEPARATOR)) {
      for (String a : ip.split(BaseConstants.COMMA_SEPARATOR)) {
        if (checkIp(ip)) {
          return a.trim();
        }
      }
    }
    return ip;
  }

  static boolean checkIp(String ip) {
    return ip != null && ip.length() > 0 && !UNKNOWN.equalsIgnoreCase(ip);
  }
}
